package com.example.wenjian.controller;


import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


@Controller
public class FileController {
    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestPart("file") MultipartFile file, Model model){
        if(file.isEmpty()){
            model.addAttribute("msg","文件为空！！");
        }
        else{
        String dirPath ="E:\\File";
        File pathFile =new File(dirPath);
        //如果路径不存在，就创建相应的文件夹
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
            String fileName=file.getOriginalFilename();
            File newFile=new File(dirPath + fileName);
        if(newFile.exists()){
            model.addAttribute("msg","已有同名文件！！");
            return "upload";
        }
        try{
            file.transferTo(newFile);
            model.addAttribute("msg","文件上传成功！！");
        }
        catch(Exception e){
            model.addAttribute("msg","文件上传失败！！");
            return "upload";
        }
        }    return "upload";
    }
    @GetMapping("/toDownload")
    public String toDownload(){
        return "download";
    }
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(String filename){
        String dirPath="E:\\File";
        File file=new File(dirPath+File.separator+filename);
        HttpHeaders headers =new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try{
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

        }catch(Exception e){
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }
}
